var logger = require('../../common').logger;
var query = require('../../common').Query;
var map = require('../../common').Mapping;

exports.findPlanDetailGroup = function (req, res) {
    if (req.body.type == 'manager') {
        query(map.sql.findPlanDetailByManager, res, req.body, function (rows) {
            res.send(rows);
        });
    } else if(req.body.type == 'project'){
        query(map.sql.findPlanDetailByProject, res, req.body, function (rows) {
            res.send(rows);
        });
    }
};

exports.findPlanDetail = function (req, res) {
    query(map.sql.findPlanDetail, res, req.body, function (rows) {
        res.send(rows);
    });
};

exports.addPlanDetail = function (req, res) {
    query(map.sql.deleteAllCurrent, res, {pm_id: req.session.uid,plan_id : parseInt(req.cookies.latest)}, function () {
        var count = 0;
        if(req.body.length == 0) {
            res.send("success");
            return;
        }
        req.body.forEach(function (e) {
            query((e.extra ? map.sql.addPlanDetail:map.sql.addPlanDetailNoExtra), res, e, function (rows) {
                if (rows.affectedRows != 0) {
                    count++;
                    if (count == req.body.length) {
                        res.send("success")
                    }
                } else {
                    res.send({error: 503, description: map.error[503]});
                    return;
                }
            });
        });
    });
};